package cn.xuqiudong.duoduo.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * 描述:
 * @author Vic.xu
 * @since 2024-04-08 16:25
 */
public class CommonIoUtils {

    public static void download(File file, HttpServletResponse response, String contentType, String filename) throws IOException {
        if (file == null || !file.exists()) {
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        if (StringUtils.isBlank(contentType)) {
            contentType = MediaType.APPLICATION_OCTET_STREAM.toString();
        }
        if (StringUtils.isBlank(filename)) {
            filename = file.getName();
        }
        response.setContentType(contentType);
        response.setHeader("Content-disposition", "attachment; filename=\"" + filename + "\"");
        try(InputStream inputStream = Files.newInputStream(file.toPath())){
            FileCopyUtils.copy(inputStream, response.getOutputStream());
        }

    }

    public static void main(String[] args) {
        MediaType applicationOctetStream = MediaType.APPLICATION_OCTET_STREAM;
        System.out.println(applicationOctetStream);
        System.out.println(applicationOctetStream.toString());
    }
}
